Before we use a function, we need to define it. The most common way to define a function in JavaScript is by using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces.
function functionName(parameters) { code to be executed }
Function Expressions A JavaScript function can also be defined using an expression. Example:
The Function() Constructor
As you have seen in the previous examples, JavaScript functions are defined with the function keyword. Functions can also be defined with a built-in JavaScript function constructor called Function().
var myFunction = new Function("a", "b", "return a * b"); document.getElementById("demo").innerHTML = myFunction(4, 3);
Function Parameters
Parameter Rules JavaScript function definitions do not specify data types for parameters. JavaScript functions do not perform type checking on the passed arguments. JavaScript functions do not check the number of arguments received.
Parameter Defaults If a function is called with missing arguments (less than declared), the missing values are set to: undefined.
function myFunction(x, y) { if (y === undefined) { y = 0; } return x * y; }
JavaScript Function Invocation Invoking a JavaScript Function You have already learned that the code inside a JavaScript function will execute when “something” invokes it. The code in a function is not executed when the function is defined. It is executed when the function is invoked. It is also quite common to say “call upon a function”, “start a function”, or “execute a function”.
Example:
function myFunction(a, b) { return a * b; } myFunction(10, 2);
Invoking a Function as a Method In JavaScript you can define function as object methods. Example:
var myObject = { firstName:"John", lastName: "Doe", fullName: function () { return this.firstName + " " + this.lastName; } } myObject.fullName();
JavaScript Closures Global Variables A function can access all variables defined inside the function. Example:
function myFunction() { var a = 4; return a * a; }
In the last example, a is a global variable. In a web page, global variables belong to the window object. A Counter Dilemma Suppose you want to use a variable for counting something, and you want this counter to be available to all functions. You could use a global variable, and a function to increase the counter: Example:
var counter = 0; function add() { counter += 1; } add(); add(); add();
JavaScript Nested Functions All functions have access to the global scope. JavaScript supports nested functions. Nested functions have access to the scope “above” them. In this example, the inner function plus() has access to the counter variable in the parent function:
function add() { var counter = 0; function plus() {counter += 1;} plus(); return counter; }
For any query contact Clofus Innovations.
Just leave your email and our support team will help you